package org.example.project_12.controller;

import jakarta.servlet.http.HttpSession;
import org.example.project_12.dto.SpaceDto;
import org.example.project_12.dto.SpaceMemberDto;
import org.example.project_12.entity.Space;
import org.example.project_12.entity.User;
import org.example.project_12.service.SpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/space")
public class SpaceController {

    @Autowired
    private SpaceService spaceService;

    @Autowired
    private org.example.project_12.service.DocumentService documentService;

    // 空间列表（我创建的）
    @GetMapping("/owned")
    public String ownedSpaces(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        List<SpaceDto> spaces = spaceService.getSpacesByOwnerId(user.getId());
        model.addAttribute("spaces", spaces);
        model.addAttribute("type", "owned");
        model.addAttribute("isLoggedIn", true);
        return "spaceList";
    }

    // 空间列表（我加入的）
    @GetMapping("/joined")
    public String joinedSpaces(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        List<SpaceDto> spaces = spaceService.getSpacesByMemberId(user.getId());
        model.addAttribute("spaces", spaces);
        model.addAttribute("type", "joined");
        model.addAttribute("isLoggedIn", true);
        return "spaceList";
    }

    // 公开空间列表
    @GetMapping("/public")
    public String publicSpaces(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        List<SpaceDto> spaces = spaceService.getPublicSpaces();
        model.addAttribute("spaces", spaces);
        model.addAttribute("type", "public");
        model.addAttribute("isLoggedIn", true);
        return "spaceList";
    }

    // 创建空间页面
    @GetMapping("/create")
    public String createSpacePage() {
        return "spaceForm";
    }

    // 创建空间处理
    @PostMapping("/create")
    public String createSpace(@RequestParam String name,
                              @RequestParam String description,
                              @RequestParam String visibility,
                              HttpSession session,
                              Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        Space space = new Space();
        space.setName(name);
        space.setDescription(description);
        space.setVisibility(visibility);
        space.setOwnerId(user.getId());
        try {
            spaceService.createSpace(space, user.getId());
            return "redirect:/space/owned";
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "spaceForm";
        }
    }

    // 编辑空间页面
    @GetMapping("/edit/{spaceId}")
    public String editSpacePage(@PathVariable Long spaceId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        SpaceDto space = spaceService.getSpaceById(spaceId, user.getId());
        model.addAttribute("space", space);
        model.addAttribute("edit", true);
        return "spaceForm";
    }

    // 编辑空间处理
    @PostMapping("/edit/{spaceId}")
    public String editSpace(@PathVariable Long spaceId,
                            @RequestParam String name,
                            @RequestParam String description,
                            @RequestParam String visibility,
                            HttpSession session,
                            Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        Space space = new Space();
        space.setId(spaceId);
        space.setName(name);
        space.setDescription(description);
        space.setVisibility(visibility);
        space.setOwnerId(user.getId());
        boolean success = spaceService.updateSpace(space, user.getId());
        if (success) {
            return "redirect:/space/owned";
        } else {
            model.addAttribute("error", "更新失败");
            model.addAttribute("space", space);
            model.addAttribute("edit", true);
            return "spaceForm";
        }
    }

    // 删除空间
    @PostMapping("/delete/{spaceId}")
    public String deleteSpace(@PathVariable Long spaceId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        spaceService.deleteSpace(spaceId, user.getId());
        return "redirect:/space/owned";
    }

    // 空间详情
    @GetMapping("/detail/{spaceId}")
    public String spaceDetail(@PathVariable Long spaceId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        org.example.project_12.dto.SpaceDto space = spaceService.getSpaceById(spaceId, user.getId());
        java.util.List<org.example.project_12.dto.DocumentDto> docs = documentService.getDocumentsBySpace(spaceId, user.getId());
        java.util.List<org.example.project_12.dto.SpaceMemberDto> members = spaceService.getSpaceMembers(spaceId, user.getId());
        boolean isOwner = user.getId().equals(space.getOwnerId());
        boolean isMember = spaceService.isUserMemberOfSpace(spaceId, user.getId());
        model.addAttribute("space", space);
        model.addAttribute("docs", docs);
        model.addAttribute("members", members);
        model.addAttribute("isOwner", isOwner);
        model.addAttribute("isMember", isMember);
        model.addAttribute("contentPage", "spaceDetail.jsp");
        model.addAttribute("activePage", "space");
        return "userLayout";
    }

    // 邀请成员
    @PostMapping("/invite/{spaceId}")
    public String inviteMember(@PathVariable Long spaceId,
                               @RequestParam Long userId,
                               @RequestParam String permission,
                               HttpSession session,
                               Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        boolean success = spaceService.inviteMember(spaceId, userId, permission, user.getId());
        if (success) {
            model.addAttribute("msg", "邀请成功");
        } else {
            model.addAttribute("error", "邀请失败");
        }
        return "redirect:/space/detail/" + spaceId;
    }

    // 移除成员
    @PostMapping("/removeMember/{spaceId}")
    public String removeMember(@PathVariable Long spaceId,
                               @RequestParam Long memberId,
                               HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        spaceService.removeMember(spaceId, memberId, user.getId());
        return "redirect:/space/detail/" + spaceId;
    }

    // 修改成员权限
    @PostMapping("/updatePermission/{spaceId}")
    public String updateMemberPermission(@PathVariable Long spaceId,
                                         @RequestParam Long memberId,
                                         @RequestParam String permission,
                                         HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) return "redirect:/user/login";
        spaceService.updateMemberPermission(spaceId, memberId, permission, user.getId());
        return "redirect:/space/detail/" + spaceId;
    }
} 